package com.das.mechanic_base.widget;

import android.app.Activity;
import android.content.Context;
import android.inputmethodservice.KeyboardView;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.das.mechanic_base.R;
import com.das.mechanic_base.adapter.main.X3LicenseNumberAdapter;
import com.das.mechanic_base.app.X3AppRouterConstants;
import com.das.mechanic_base.app.X3Constent;
import com.das.mechanic_base.app.X3RouterCenter;
import com.das.mechanic_base.base.X3BaseBottomSheetDialog;
import com.das.mechanic_base.base.X3IBaseView;
import com.das.mechanic_base.bean.live.LiveSelectCarBean;
import com.das.mechanic_base.bean.main.CarMemberBean;
import com.das.mechanic_base.bean.main.CarModelSelectBean;
import com.das.mechanic_base.bean.main.CarPoolBean;
import com.das.mechanic_base.bean.main.CarPoolMainBean;
import com.das.mechanic_base.bean.main.VlideCarNumBean;
import com.das.mechanic_base.gen.DaoSessionUtils;
import com.das.mechanic_base.mapi.api.NetWorkHttp;
import com.das.mechanic_base.mapi.response.HttpCallBack;
import com.das.mechanic_base.mapi.schedulers.RxSchedulersHelper;
import com.das.mechanic_base.utils.SpHelper;
import com.das.mechanic_base.utils.SpaceFilter;
import com.das.mechanic_base.utils.X3KeyboardUtil;
import com.das.mechanic_base.utils.X3StringUtils;
import com.das.mechanic_base.utils.X3ToastUtils;
import com.das.mechanic_base.utils.X3Utils;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class X3BottomQuickCarDialog extends X3BaseBottomSheetDialog implements View.OnClickListener, TextWatcher, TextView.OnEditorActionListener, X3SelectCarPopuWindow.OnAdapterItemClick, X3MemberButtonView.IOnClickAffirm, X3LicenseNumberAdapter.ItemOnclick {

    private EditText et_car_num;
    private ImageView iv_take;
    private TextView tv_notice;
    private TextView tv_cancel;
    private X3MemberButtonView btn_creat;
    private RelativeLayout sl_view;

    private PopupWindow keyPop;

    private String serviceBaseSn;
    private long receiveId;

    private TextView tv_recent;
    private TextView tv_search;
    private LinearLayout ll_recent;
    private X3LicenseNumberAdapter licenseNumberAdapter;
    private String mobile;
    private CarPoolBean selectCarPoolBean;
    private RecyclerView rlv_number;
    private List<LiveSelectCarBean> dataList;

    public X3BottomQuickCarDialog(@NonNull Context context) {
        super(context);
    }

    @Override
    protected boolean getDialogCancel() {
        return false;
    }

    @Override
    protected void initView() {
        iv_take = getView(R.id.iv_take);
        et_car_num = getView(R.id.et_car_num);
        tv_notice = getView(R.id.tv_notice);
        btn_creat = getView(R.id.btn_creat);
        tv_cancel = getView(R.id.tv_cancel);
        sl_view = getView(R.id.sl_view);
        rlv_number = getView(R.id.rlv_number);
        tv_recent = getView(R.id.tv_recent);
        tv_search = getView(R.id.tv_search);
        ll_recent = getView(R.id.ll_recent);
        tv_search.setOnClickListener(this);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, 2);
        rlv_number.setLayoutManager(gridLayoutManager);
        licenseNumberAdapter = new X3LicenseNumberAdapter(mContext);
        rlv_number.setAdapter(licenseNumberAdapter);
        licenseNumberAdapter.setOnitemClick(this);
        mobile = (String) SpHelper.getData("mobile", "");
        iv_take.setOnClickListener(this);
        tv_cancel.setOnClickListener(this);
        et_car_num.addTextChangedListener(this);
        et_car_num.setOnClickListener(this);

        btn_creat.setiOnClickAffirm(this);

        et_car_num.setFilters(new InputFilter[]{new SpaceFilter()});

        et_car_num.setOnEditorActionListener(this);

        if (X3Constent.isChina()) {
            initKeyView();
        }
    }

    public void setCarNum(String carNum) {
        if (X3StringUtils.isEmpty(carNum)) {
            return;
        }
        et_car_num.setText(carNum);
        et_car_num.setSelection(carNum.length());
        searchNum(carNum);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.x3_bottom_quick_car_item;
    }

    private X3KeyboardUtil keyboardUtil;

    public void changeMainQuickBean(String serviceBaseSn) {
        this.serviceBaseSn = serviceBaseSn;
    }

    private void initKeyView() {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            et_car_num.setShowSoftInputOnFocus(false);
//        }
        View view = View.inflate(mContext, R.layout.x3_keyboard_pop, null);
        KeyboardView keyView = view.findViewById(R.id.keyboard_view);
        keyPop = new PopupWindow(view, RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        keyPop.setFocusable(true);
        keyPop.setBackgroundDrawable(null);
        keyPop.setOutsideTouchable(true);
        keyboardUtil = new X3KeyboardUtil((Activity) mContext, keyView, et_car_num);
        keyboardUtil.hideSoftInputMethod();
        keyPop.setOnDismissListener(() -> {
            if (keyboardUtil != null) {
                keyboardUtil.hideSoftInputMethod();
                keyboardUtil.hideKeyboard();
            }
        });
    }

    private Handler mHandler = new Handler();

    private Runnable runnable = () -> showWorkInput();

    @Override
    public void dismiss() {
        if (mHandler != null) {
            mHandler.removeCallbacks(runnable);
        }
        super.dismiss();
    }

    @Override
    public void show() {
        super.show();
        et_car_num.setText("");

        tv_notice.setVisibility(View.GONE);

        if (mHandler != null) {
            mHandler.postDelayed(runnable,200);
        }
    }

    public void showWorkInput() {
        et_car_num.setFocusable(true);
        et_car_num.setFocusableInTouchMode(true);
        et_car_num.requestFocus();
        if (X3Constent.isChina()) {
            et_car_num.performClick();
        }else {
            X3Utils.showInput(et_car_num,mContext);
        }
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_take) {// 调用拍照
            if (iOnClick != null) {

                iOnClick.iOnClikCamera();
            }
        } else if (id == R.id.tv_cancel) {
            dismiss();
        } else if (id == R.id.et_car_num) {
            if (X3Constent.isChina()) {
                if (keyPop.isShowing()) {
                    keyPop.dismiss();
                } else {
                    String s = et_car_num.getText().toString();
                    if (!X3StringUtils.isEmpty(s) && s.length() >= 1) {
                        // 已经输入了省代码
                        keyboardUtil.changeKeyboard(true);
                    } else {
                        keyboardUtil.changeKeyboard(false);
                    }
                    keyPop.showAtLocation(sl_view, Gravity.BOTTOM, 0, 0);
                    keyboardUtil.showKeyboard();
                }
            }
        } else if (id == R.id.tv_search) {
            X3CarPoolDailog carPoolDailog = new X3CarPoolDailog(mContext);
            carPoolDailog.show();
            carPoolDailog.setOnItemClick(carPoolBean -> {
                carPoolDailog.dismiss();
                selectCarPoolBean = carPoolBean;
                et_car_num.setText(carPoolBean.label);
                et_car_num.setSelection(carPoolBean.label.length());
                btn_creat.performClick();
            });
            //车辆池
            NetWorkHttp.getApi().listStoreAllCarNum()
                    .compose(((X3IBaseView) mContext).bindToLife())
                    .compose(RxSchedulersHelper.defaultComposeRequest())
                    .subscribe(new HttpCallBack<CarPoolMainBean>() {
                        @Override
                        protected void onDone(CarPoolMainBean carPoolMainBean) {
                            if (carPoolMainBean == null) {
                                X3ToastUtils.showMessage(mContext.getString(R.string.x3_home_no_select));
                                return;
                            }
                            if (X3StringUtils.isListEmpty(carPoolMainBean.list)) {
                                X3ToastUtils.showMessage(mContext.getString(R.string.x3_home_no_select));
                                return;
                            } else {
                                if (carPoolDailog != null) {
                                    List<CarModelSelectBean> selectLists = new ArrayList<>();
                                    carPoolDailog.changeData(mContext.getString(R.string.car_pool), carPoolMainBean.list, selectLists);
                                }
                            }
                        }

                        @Override
                        protected String LoadingMessage() {
                            return null;
                        }

                        @Override
                        protected void showError(String error) {

                        }
                    });
        }
    }

    private void createServiceVariant(Map<String, Object> map) {
        NetWorkHttp.getApi().saveSafeDetection(map)
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .compose(((X3IBaseView)mContext).bindToLife())
                .subscribe(new HttpCallBack<VlideCarNumBean>() {
                    @Override
                    protected void onDone(VlideCarNumBean validCarBean) {
                        btn_creat.reset();
                        selectCarPoolBean = null;
                        EventBus.getDefault().post("UPDATE_START_ORDER");
                        if (validCarBean == null) {
                            return;
                        }
                        if (validCarBean.receiveBaseId == null) {
                            return;
                        }
                        if (validCarBean.workBaseId == null) {
                            return;
                        }
                        dismiss();
                        Bundle bundle = new Bundle();
                        bundle.putLong("receiveBaseId",validCarBean.receiveBaseId);
                        bundle.putLong("id",validCarBean.workBaseId);
                        bundle.putBoolean("isQuick",true);
                        X3RouterCenter.startNavigate(X3AppRouterConstants.Router.MAIN_TAIN,bundle);
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {
                        btn_creat.reset();
                        selectCarPoolBean = null;
                    }
                });

    }

    IOnClick iOnClick;

    public void setiOnClick(IOnClick iOnClick) {
        this.iOnClick = iOnClick;
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
        if (charSequence == null) {
            return;
        }

        if (charSequence.toString().contains(" ")) {
            String[] str = charSequence.toString().split(" ");
            StringBuffer sb = new StringBuffer();
            for (int j = 0; j < str.length; j++) {
                sb.append(str[j]);
            }
            if (!X3StringUtils.isEmpty(sb.toString())) {
                et_car_num.setText(sb.toString());
                et_car_num.setSelection(sb.length());
            }
        }


    }

    @Override
    public void afterTextChanged(Editable editable) {
        if (editable == null) {
            return;
        }
        int index = et_car_num.getSelectionStart() - 1;
        if (index > 0) {

            if (X3StringUtils.isEmojiCharacter(editable.charAt(index))) {
                Editable edit = et_car_num.getText();
                edit.delete(editable.length() - 2, editable.length());
                et_car_num.setText(edit.toString());

                return;
            }
        }
        //去除空格
        String carNum = editable.toString().replaceAll(" ", "");

        if (X3StringUtils.isEmpty(carNum)) {
            btn_creat.changeBtnStatus(false);
            return;
        }
        btn_creat.changeBtnStatus(true);

        //转大写
        String newCarNum = carNum.toUpperCase();
        Matcher matcher = pattern.matcher(carNum);
        if (matcher.matches()) {
            et_car_num.setText(newCarNum);
            et_car_num.setSelection(newCarNum.length());
        }

        if(carNum.length() >= 2) {
            // 搜索车牌号
            searchNum(newCarNum);
            HashMap<String, Object> map = new HashMap<>();
            map.put("keyword", carNum);
            searchCarMember(map);
        }else {
            initData();
        }

//        if(carNum.length() >= 2){
//            if(StringUtils.isEmpty(carNum)){
//                searchCarMember(new HashMap<>());
//            }else {
//                HashMap<String,Object> map = new HashMap<>();
//                map.put("keyword",carNum);
//                searchCarMember(map);
//            }
//        }else {
//            initData();
//        }

    }

    /**
     * 搜索车牌号接口
     */
    private void searchCarMember(HashMap<String,Object> map){
        NetWorkHttp.getApi().listStoreCarNumReceive(map)
                .compose(((X3IBaseView)mContext).bindToLife())
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new HttpCallBack<List<LiveSelectCarBean>>() {
                    @Override
                    protected void onDone(List<LiveSelectCarBean> list) {
                        if(X3StringUtils.isListEmpty(list)){
                            return;
                        }
                        dataList = list;
                        //刷新数据
                        if(licenseNumberAdapter == null){
                            return;
                        }
                        ll_recent.setVisibility(View.VISIBLE);
                        tv_search.setVisibility(View.VISIBLE);
                        tv_recent.setVisibility(View.VISIBLE);
                        rlv_number.setVisibility(View.VISIBLE);
                        licenseNumberAdapter.setData(list);

                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

    public void initData() {
        //数据库查询最近搜索的车牌
        CarMemberBean carMemberBean = DaoSessionUtils.getInstance().searchCarMemberBean( mobile+ "车牌号");
        if(carMemberBean == null){
            ll_recent.setVisibility(View.GONE);
        }else {
            if(X3StringUtils.isListEmpty(carMemberBean.getList())){
                ll_recent.setVisibility(View.GONE);
            }else {
                ll_recent.setVisibility(View.VISIBLE);
                tv_search.setVisibility(View.GONE);
                tv_recent.setVisibility(View.VISIBLE);
                rlv_number.setVisibility(View.VISIBLE);
                licenseNumberAdapter.setData(carMemberBean.getList());
            }
        }
    }

    /**
     * 搜索车牌号下 是否有未支付的订单
     * @param newCarNum
     */
    private void searchNum(String newCarNum) {
        tv_notice.setVisibility(View.GONE);
        NetWorkHttp.getApi().validReceivePayStatus(newCarNum)
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .compose(((X3IBaseView)mContext).bindToLife())
                .subscribe(new HttpCallBack<VlideCarNumBean>() {
                    @Override
                    protected void onDone(VlideCarNumBean vlideCarNumBean) {
                        if (vlideCarNumBean == null) {
                            receiveId = 0L;
                            return;
                        }
                        Long receiveBaseId = vlideCarNumBean.receiveBaseId;
                        if (receiveBaseId == null) {
                            receiveId = 0L;
                            return;
                        }
                        receiveId = receiveBaseId;
                        tv_notice.setVisibility(View.VISIBLE);
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });

    }

    private Pattern pattern = Pattern.compile(".*[a-z]+.*");

    @Override
    public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
        if (i == EditorInfo.IME_ACTION_SEARCH) {
            String carNum = et_car_num.getText().toString();
            searchNum(carNum);
        }
        return true;
    }

    @Override
    public void onAdapterClick(String carNum) {
        if (!X3StringUtils.isEmpty(carNum)) {
            et_car_num.setText(carNum);
            et_car_num.setSelection(carNum.length());
        }
        searchNum((carNum));
    }

    @Override
    public void iOnClickAffirm() {
        // 创建安全检测施工单
        if (!X3Utils.isFastClick()) {
            return;
        }

        String carNum = et_car_num.getText().toString();
        if (X3StringUtils.isEmpty(carNum)) {
            btn_creat.reset();
            return;
        }
        if (X3StringUtils.isEmpty(serviceBaseSn)) {
            btn_creat.reset();
            return;
        }

        if(selectCarPoolBean == null){//null代表手动输入的  不为null则是点击获取的
            selectCarPoolBean = new CarPoolBean();
            selectCarPoolBean.label = et_car_num.getText().toString();
            selectCarPoolBean.kwParam = new CarPoolBean.KwParamBean();
            selectCarPoolBean.kwParam.carBrandImgUrl = "";
            if(!X3StringUtils.isListEmpty(dataList)){
                for (int i =0; i < dataList.size();i++){
                    if(selectCarPoolBean.label.equals(dataList.get(i).num.replaceAll("<em>","").replaceAll("</em>",""))){
                        selectCarPoolBean.kwParam.carBrandImgUrl = dataList.get(i).carBrandImgUrl;
                    }
                }
            }
        }
        //车牌号存储到数据库
        CarMemberBean carMemberBean = DaoSessionUtils.getInstance().searchCarMemberBean( mobile+ "车牌号");
        if(carMemberBean == null){
            carMemberBean = new CarMemberBean();
            List<LiveSelectCarBean> list =   new ArrayList<>();
            LiveSelectCarBean liveSelectCarBean = new LiveSelectCarBean();
            liveSelectCarBean.carBrandImgUrl= selectCarPoolBean.kwParam.carBrandImgUrl;
            liveSelectCarBean.num = selectCarPoolBean.label;
            list.add(liveSelectCarBean);
            carMemberBean.setList(list);
            carMemberBean.setCarName(mobile+"车牌号");
            DaoSessionUtils.getInstance().insertCarMemberBean(carMemberBean);
        }else{
            List<LiveSelectCarBean> list = carMemberBean.getList();
            if(X3StringUtils.isListEmpty(list)){
                list = new ArrayList<>();
            }
            boolean isEqual = false;
            for (LiveSelectCarBean liveSelectCarBean : list) {
                if (!liveSelectCarBean.num.equals(selectCarPoolBean.label)) {
                    continue;
                }
                isEqual = true;
                break;
            }
            if(!isEqual){
                if(list.size() >= 6){
                    Collections.reverse(list);
                    list.remove(0);
                    LiveSelectCarBean liveSelectCarBean = new LiveSelectCarBean();
                    liveSelectCarBean.carBrandImgUrl= selectCarPoolBean.kwParam.carBrandImgUrl;
                    liveSelectCarBean.num = selectCarPoolBean.label;
                    carMemberBean.setCarName(mobile+"车牌号");
                    list.add(liveSelectCarBean);
                    Collections.reverse(list);
                    carMemberBean.setList(list);
                    DaoSessionUtils.getInstance().updateCarMemberBean(carMemberBean);
                }else {
                    LiveSelectCarBean liveSelectCarBean = new LiveSelectCarBean();
                    liveSelectCarBean.carBrandImgUrl= selectCarPoolBean.kwParam.carBrandImgUrl;
                    liveSelectCarBean.num = selectCarPoolBean.label;
                    carMemberBean.setCarName(mobile+"车牌号");
                    Collections.reverse(list);
                    list.add(liveSelectCarBean);
                    Collections.reverse(list);
                    carMemberBean.setList(list);
                    DaoSessionUtils.getInstance().insertCarMemberBean(carMemberBean);
                }
            } else {//车牌号相同时 更新图标
                if(!X3StringUtils.isListEmpty(dataList)){
                    for(int i =0; i < list.size();i++){
                        if(X3StringUtils.isEmpty(list.get(i).carBrandImgUrl)){
                            list.get(i).carBrandImgUrl = selectCarPoolBean.kwParam.carBrandImgUrl;
                            carMemberBean.setList(list);
                            carMemberBean.setCarName(mobile+"车牌号");
                            DaoSessionUtils.getInstance().updateCarMemberBean(carMemberBean);
                        }
                    }
                }

            }
        }
        Map<String,Object> map = new HashMap<>();
        map.put("carNum",carNum);
        if (receiveId > 0) {
            map.put("receiveBaseId",receiveId);
        }
        map.put("serviceBaseSn",serviceBaseSn);
        createServiceVariant(map);
    }

    @Override
    public void onItemClick(String carNum, String imgUrl) {
        selectCarPoolBean = new CarPoolBean();
        selectCarPoolBean.label = carNum;
        selectCarPoolBean.kwParam = new CarPoolBean.KwParamBean();
        selectCarPoolBean.kwParam.carBrandImgUrl = imgUrl;
        et_car_num.setText(carNum);
        et_car_num.setSelection(carNum.length());
        btn_creat.performClick();
    }

    public interface IOnClick {
        void iOnClikCamera();

        void iOnRefresh();
    }

    @Override
    protected void onStart() {
        super.onStart();
        MobclickAgent.onPageStart("快速检测车牌号弹窗");
    }

    @Override
    protected void onStop() {
        super.onStop();
        MobclickAgent.onPageEnd("快速检测车牌号弹窗");
    }

    public void  isShowdata(){
        CarMemberBean carMemberBean = DaoSessionUtils.getInstance().searchCarMemberBean( mobile+ "车牌号");
        if(carMemberBean == null){
            ll_recent.setVisibility(View.GONE);
        }else {
            if(X3StringUtils.isListEmpty(carMemberBean.getList())){
                ll_recent.setVisibility(View.GONE);
            }else {
                List<LiveSelectCarBean> carList = carMemberBean.getList();
                List<String> imfUlrList = new ArrayList<>();
                for (int i = 0; i < carList.size(); i++){
                    imfUlrList.add(carList.get(i).num);
                }
                listStoreCarIcon(imfUlrList);
            }
        }

    }
    /**
     * 获取店铺车辆品牌图标
     */
    private void listStoreCarIcon(List<String> list){
        NetWorkHttp.getApi().listStoreCarIcon(list)
                .compose(((X3IBaseView)mContext).bindToLife())
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new HttpCallBack<List<String>>() {
                    @Override
                    protected void onDone(List<String> datalist) {
                        if(X3StringUtils.isListEmpty(datalist)){
                            initData();
                            return;
                        }

                        CarMemberBean carMemberBean = DaoSessionUtils.getInstance().searchCarMemberBean( mobile+ "车牌号");
                        if(carMemberBean == null){
                            ll_recent.setVisibility(View.GONE);
                        }else {
                            if(X3StringUtils.isListEmpty(carMemberBean.getList())){
                                ll_recent.setVisibility(View.GONE);
                            }else {
                                List<LiveSelectCarBean> carList = carMemberBean.getList();
                                for (int i =0; i < carList.size(); i++){
                                    if(!X3StringUtils.isEmpty(datalist.get(i))){
                                        carList.get(i).carBrandImgUrl = datalist.get(i);
                                    }
                                }
                                carMemberBean.setCarName(mobile+"车牌号");
                                carMemberBean.setList(carList);
                                DaoSessionUtils.getInstance().updateCarMemberBean(carMemberBean);
                                CarMemberBean carBean = DaoSessionUtils.getInstance().searchCarMemberBean( mobile+ "车牌号");
                                ll_recent.setVisibility(View.VISIBLE);
                                tv_search.setVisibility(View.GONE);
                                tv_recent.setVisibility(View.VISIBLE);
                                rlv_number.setVisibility(View.VISIBLE);
                                licenseNumberAdapter.setData(carBean.getList());
                            }
                        }

                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {
                        initData();
                    }
                });
    }

}
